#!/usr/bin/python
# -*- coding: utf-8 -*-

import time
import urllib
import simplejson

def Score(data):
    pv = data[3]
    totalcomment = data[4]
    fav = data[5]
    updown = data[6] - data[7]
    reference = data[8]
    return fav


def MyCmp(data1, data2):
    if Score(data1) > Score(data2):
    	return -1
    return 1

#通过API获取本月视频信息
url = 'http://api.youku.com/api_getHotVideos/pid/XMTI5Mg==/period/week/pn/1/pl/1/'
youku_json = urllib.urlopen(url).read()
data = simplejson.loads(youku_json)
total_video = data['total']

page_id = 1
page_cnt = total_video / 100 + 1
while page_id <= 10:
    url = 'http://api.youku.com/api_getHotVideos/pid/XMTI5Mg==/period/month/pn/' + str(page_id) + '/'
    youku_json = urllib.urlopen(url).read()
    data = simplejson.loads(youku_json)
    results = data['results']
    print page_id
    for item in results:
    	print item['total_fav'], item['title'].encode('utf-8'), item['createtime']
    page_id = page_id + 1

exit(0)

#得到10-30天前的日期 (9,30)
ISOTIMEFORMAT='%Y-%m-%d'
cur_time = time.time()
from_time = cur_time - 13 * 24 * 3600;
from_time_str = time.strftime(ISOTIMEFORMAT, time.localtime(from_time))
to_time = cur_time - 9 * 24 * 3600;
to_time_str = time.strftime(ISOTIMEFORMAT, time.localtime(to_time))

#将top100的视频信息写入xml, json
output = open('pop_sorted.xml', 'w')
output2 = open('pop_sorted.json', 'w')
output.write("<xml>\n")
output2.write("{\"images\":[\n")

for i in range(0, 100):
	output.write("<item>\n")
	output.write("<id>" + list[i][0] + "</id>\n")
	output.write("<title><![CDATA[" + list[i][1] + "]]></title>\n") 
	output.write("<thumbnail><![CDATA[" + list[i][2] + "]]></thumbnail>\n")
	output.write("<pv>" + str(list[i][3]) + "</pv>\n")
	output.write("<totalcomment>" + str(list[i][4]) + "</totalcomment>\n")
	output.write("<fav>" + str(list[i][5]) + "</fav>\n")
	output.write("<up>" + str(list[i][6]) + "</up>\n")
	output.write("<down>" + str(list[i][7]) + "</down>\n")
	output.write("<reference>" + str(list[i][8]) + "</reference>\n")
	output.write("<pubdate>" + str(list[i][9]) + "</pubdate>\n")
	output.write("<playlink><![CDATA[" + list[i][10] + "]]></playlink>\n")
	output.write("</item>\n")

for i in range(0, 50):
    output2.write("{\"src\":\"" + list[i][2] + "\", \"title\":\"" + list[i][1] + "\", \"href\":\"" + \
            "http://player.youku.com/player.php/sid/" + list[i][0] + "/partnerid/XMTI5Mg==/v.swf\", " + \
            "\"playlink\":\"" + list[i][10] + "\"}")
    if i != 49:
    	output2.write(',')
    output2.write('\n')

output.write("</xml>\n")
output2.write("]}\n")
output.close()
output2.close()

cur.close()
conn.close()
